<template>
  <PageContainer>
    <section class="content-block">
      <div class="section-header">
        <h2>团队介绍</h2>
        <p class="section-desc">跨学科小组协作打造平台，从产品策划到技术实现提供全流程支撑。</p>
      </div>
      <AsyncState
        :loading="teamLoading"
        :error="teamError"
        :isEmpty="!teamCards.length"
        emptyMessage="暂未获取到团队信息"
        :retry="fetchTeam"
      >
        <div class="grid">
          <InfoCard
            v-for="member in teamCards"
            :key="member.id"
            :title="member.name"
            :description="member.role"
            :meta="member.meta"
            :tags="member.skills"
          >
            <template #footer>
              <a
                v-if="member.email"
                :href="`mailto:${member.email}`"
                class="contact-link"
              >
                联系 {{ member.name }}
              </a>
            </template>
          </InfoCard>
        </div>
      </AsyncState>
    </section>

    <section class="content-block">
      <div class="section-header">
        <h2>版本演进</h2>
        <p class="section-desc">追踪平台的功能迭代与体验优化，一览关键里程碑与亮点更新。</p>
      </div>
      <AsyncState
        :loading="versionLoading"
        :error="versionError"
        :isEmpty="!versionTimeline.length"
        emptyMessage="暂无版本记录"
        :retry="fetchVersions"
      >
        <div class="version-timeline-container" ref="containerRef">
          <!-- 时间轴 -->
          <el-scrollbar 
            class="timeline-scrollbar" 
            ref="timelineScrollbarRef"
            @scroll="handleTimelineScroll"
          >
            <div class="timeline-axis-horizontal" ref="timelineAxisRef">
              <div class="axis-line-horizontal"></div>
              <div
                v-for="(item, index) in versionTimeline"
                :key="`timeline-${item.version}`"
                class="timeline-node-horizontal"
                :class="{ 'is-latest': index === versionTimeline.length - 1 }"
                :ref="el => setTimelineNodeRef(el, index)"
              >
                <div class="node-dot-horizontal"></div>
                <div class="node-date-horizontal">{{ formatDateOnly(item.date) }}</div>
              </div>
            </div>
          </el-scrollbar>
          
          <!-- 版本卡片 -->
          <el-scrollbar 
            class="version-scrollbar"
            ref="versionScrollbarRef"
            @scroll="handleVersionScroll"
          >
            <div class="version-timeline-horizontal" ref="versionCardsRef">
              <div
                v-for="(item, index) in versionTimeline"
                :key="item.version"
                class="version-item-wrapper"
                :ref="el => setCardRef(el, index)"
              >
                <el-card
                  class="version-card"
                  :class="{ 'is-latest': index === versionTimeline.length - 1 }"
                  shadow="hover"
                >
                  <template #header>
                    <div class="card-header">
                      <el-tag
                        :type="index === versionTimeline.length - 1 ? 'success' : 'primary'"
                        size="large"
                        effect="dark"
                      >
                        {{ item.version }}
                      </el-tag>
                      <span class="version-date">{{ formatDateOnly(item.date) }}</span>
                    </div>
                  </template>
                  <div class="card-body">
                    <p class="version-summary">{{ item.summary }}</p>
                    <el-divider v-if="item.highlights?.length" />
                    <ul v-if="item.highlights?.length" class="highlight-list">
                      <li v-for="highlight in item.highlights" :key="highlight">
                        <el-icon class="highlight-icon"><Check /></el-icon>
                        <span>{{ highlight }}</span>
                      </li>
                    </ul>
                  </div>
                </el-card>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </AsyncState>
    </section>
  </PageContainer>
</template>

<script setup>
import { computed, onMounted, ref, nextTick, watch } from 'vue'
import { ElScrollbar, ElCard, ElTag, ElDivider, ElIcon } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import PageContainer from '../components/PageContainer.vue'
import AsyncState from '../components/AsyncState.vue'
import InfoCard from '../components/InfoCard.vue'
import { getMetaTeam, getMetaVersion } from '../api/client'
import { useAsyncData } from '../composables/useAsyncData'
import { formatDateOnly } from '../utils/formatters'

const containerRef = ref(null)
const timelineScrollbarRef = ref(null)
const versionScrollbarRef = ref(null)
const timelineAxisRef = ref(null)
const versionCardsRef = ref(null)
const timelineNodeRefs = ref([])
const cardRefs = ref([])
let isScrolling = false

function setTimelineNodeRef(el, index) {
  if (el) {
    timelineNodeRefs.value[index] = el
  }
}

function setCardRef(el, index) {
  if (el) {
    cardRefs.value[index] = el
  }
}

function updateTimelinePositions() {
  if (!versionCardsRef.value || !timelineAxisRef.value || cardRefs.value.length === 0) {
    return
  }
  
  nextTick(() => {
    const cardsContainer = versionCardsRef.value
    const axisContainer = timelineAxisRef.value
    const cardsContainerWidth = cardsContainer.scrollWidth
    const axisContainerWidth = axisContainer.scrollWidth
    
    if (cardsContainerWidth === 0 || axisContainerWidth === 0) {
      return
    }
    
    cardRefs.value.forEach((cardEl, index) => {
      if (!cardEl || !timelineNodeRefs.value[index]) return
      
      const cardRect = cardEl.getBoundingClientRect()
      const containerRect = cardsContainer.getBoundingClientRect()
      const cardLeft = cardRect.left - containerRect.left + cardRect.width / 2
      const percentage = (cardLeft / cardsContainerWidth) * 100
      
      timelineNodeRefs.value[index].style.left = `${percentage}%`
    })
  })
}

function handleTimelineScroll() {
  if (isScrolling) return
  isScrolling = true
  
  const timelineWrap = timelineScrollbarRef.value?.wrapRef
  const versionWrap = versionScrollbarRef.value?.wrapRef
  
  if (timelineWrap && versionWrap) {
    const scrollLeft = timelineWrap.scrollLeft
    const maxScrollLeft = timelineWrap.scrollWidth - timelineWrap.clientWidth
    const versionMaxScrollLeft = versionWrap.scrollWidth - versionWrap.clientWidth
    
    if (versionMaxScrollLeft > 0) {
      const ratio = scrollLeft / maxScrollLeft
      versionWrap.scrollLeft = ratio * versionMaxScrollLeft
    }
  }
  
  setTimeout(() => {
    isScrolling = false
  }, 10)
}

function handleVersionScroll() {
  if (isScrolling) return
  isScrolling = true
  
  const timelineWrap = timelineScrollbarRef.value?.wrapRef
  const versionWrap = versionScrollbarRef.value?.wrapRef
  
  if (timelineWrap && versionWrap) {
    const scrollLeft = versionWrap.scrollLeft
    const maxScrollLeft = versionWrap.scrollWidth - versionWrap.clientWidth
    const timelineMaxScrollLeft = timelineWrap.scrollWidth - timelineWrap.clientWidth
    
    if (timelineMaxScrollLeft > 0) {
      const ratio = scrollLeft / maxScrollLeft
      timelineWrap.scrollLeft = ratio * timelineMaxScrollLeft
    }
  }
  
  updateTimelinePositions()
  
  setTimeout(() => {
    isScrolling = false
  }, 10)
}

const {
  data: teamMembers,
  loading: teamLoading,
  error: teamError,
  execute: fetchTeam,
} = useAsyncData(getMetaTeam, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

const {
  data: versionLog,
  loading: versionLoading,
  error: versionError,
  execute: fetchVersions,
} = useAsyncData(getMetaVersion, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})


const teamCards = computed(() =>
  teamMembers.value.map((member) => ({
    ...member,
    meta: [
      {
        label: '擅长领域',
        value: (member.skills || []).join('、') || '未填写',
      },
    ],
    skills: member.skills ?? [],
    email: member.contact?.email,
  })),
)

const versionTimeline = computed(() =>
  versionLog.value
    .slice()
    .sort((a, b) => new Date(a.date || 0) - new Date(b.date || 0)),
)

watch(versionTimeline, () => {
  nextTick(() => {
    updateTimelinePositions()
  })
}, { deep: true })

onMounted(() => {
  fetchTeam().catch(() => {})
  fetchVersions().catch(() => {})
  
  nextTick(() => {
    updateTimelinePositions()
    // 监听窗口大小变化
    window.addEventListener('resize', updateTimelinePositions)
  })
})
</script>

<style scoped>
.content-block {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-header {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.section-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

.section-desc {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.contact-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

.contact-link:hover {
  text-decoration: underline;
}

.version-timeline-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.timeline-scrollbar {
  width: 100%;
  padding: 0;
}

.timeline-scrollbar :deep(.el-scrollbar__wrap) {
  overflow-x: auto;
  overflow-y: hidden;
}

.timeline-scrollbar :deep(.el-scrollbar__bar) {
  bottom: 0;
}

.timeline-scrollbar :deep(.el-scrollbar__arrow) {
  display: none;
}

.timeline-axis-horizontal {
  position: relative;
  height: 100px;
  min-width: max-content;
  padding: 0 20px;
  margin: 20px 0;
}

.axis-line-horizontal {
  position: absolute;
  top: 50px;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(to right, #409eff, #67c23a);
  border-radius: 2px;
  width: 100%;
}

.timeline-node-horizontal {
  position: absolute;
  top: 0;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  transition: left 0.3s ease;
}

.node-dot-horizontal {
  width: 16px;
  height: 16px;
  background: #fff;
  border: 4px solid #409eff;
  border-radius: 50%;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
  transition: all 0.3s ease;
}

.timeline-node-horizontal.is-latest .node-dot-horizontal {
  width: 20px;
  height: 20px;
  border-width: 5px;
  border-color: #67c23a;
  box-shadow: 0 0 0 4px rgba(103, 194, 58, 0.2);
}

.node-date-horizontal {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  font-weight: 500;
}

.timeline-node-horizontal.is-latest .node-date-horizontal {
  color: #67c23a;
  font-weight: 600;
}

.version-scrollbar {
  width: 100%;
  padding: 20px 0;
}

.version-scrollbar :deep(.el-scrollbar__wrap) {
  overflow-x: auto;
  overflow-y: hidden;
}

.version-scrollbar :deep(.el-scrollbar__bar) {
  bottom: 0;
}

.version-scrollbar :deep(.el-scrollbar__arrow) {
  display: none;
}

.version-timeline-horizontal {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 20px 0;
  min-width: max-content;
}

.version-item-wrapper {
  display: flex;
  align-items: flex-start;
  flex-shrink: 0;
}

.version-card {
  width: 320px;
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.version-card:hover {
  transform: translateY(-4px);
}

.version-card.is-latest {
  border-color: rgba(103, 194, 58, 0.4);
}

.version-card.is-latest :deep(.el-card__header) {
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.05), rgba(255, 255, 255, 1));
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.version-date {
  font-size: 13px;
  color: #909399;
  white-space: nowrap;
  font-weight: 500;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.version-summary {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.highlight-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.highlight-list li {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

.highlight-icon {
  color: #67c23a;
  flex-shrink: 0;
  margin-top: 2px;
  font-size: 16px;
}

@media (max-width: 960px) {
  .version-card {
    width: 280px;
  }
}

@media (max-width: 640px) {
  .version-card {
    width: 260px;
  }
}

@media (max-width: 640px) {
  .grid {
    grid-template-columns: 1fr;
  }
}
</style>

